package com.vidmt.api.modules.sys.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.service.CrudService;
import com.vidmt.api.modules.sys.Enums.OrderStatus;
import com.vidmt.api.modules.sys.Enums.PayEvent;
import com.vidmt.api.modules.sys.dao.OrderDao;
import com.vidmt.api.modules.sys.entity.Order;
import com.vidmt.api.modules.sys.entity.Paylog;
import com.vidmt.api.modules.sys.entity.Role;
import com.vidmt.api.modules.sys.entity.sub.RoleLvl;
import com.vidmt.api.modules.sys.utils.UserStatUtil;

@Service
@Transactional(readOnly = false)
public class OrderService extends CrudService<OrderDao, Order> {
	@Autowired
	private UserService userService;
	@Autowired
	private PaylogService paylogService;
	@Autowired
	private RoleService roleService;

	@Transactional(readOnly = true)
	public Order load(String id) {
		return dao.load(id);
	}
	
	@Transactional(readOnly = true)
	public List<Order> findLatest(Date date) {
		return dao.findLatest(date);
	}

	@Transactional(readOnly = true)
	public Order findTotalFee(Date start) {
		return dao.findTotalFee(start);
	}

	@Transactional(readOnly = true)
	public Order findByTradeno(String tradeno) {
		return dao.findByTradeno(tradeno);
	}

	@Transactional(readOnly = true)
	public List<Order> findByUid(Long uid) {
		return dao.findByUid(uid);
	}

	public void refund(Order order, String allparams) {
		order.setRefundTime(new Date());
		dao.updateStatus(OrderStatus.REFUND, order.getId());
		userService.updateUserExpired(order.getUid());
		Paylog paylog = new Paylog();
		paylog.setUid(order.getUid());
		paylog.setPayEvent(PayEvent.REFUND);
		paylog.setPayType(order.getPayType());
		paylog.setPayTime(order.getPayTime());
		paylog.setTotalFee(order.getTotalFee());
		paylog.setTradeNo(order.getTradeNo());
		paylog.setContent(allparams);
		paylogService.save(paylog);
	}
	
	public void paysuccess(Order order, String allparams) {
		UserStatUtil.putPay(order.getPayType(), order.getTotalFee());

		this.update(order);
		Role role = roleService.getRoleByKey(order.getLvlType().name());
		RoleLvl lvl = new RoleLvl(role);

		userService.updateUserPayed(order.getUid(), lvl);

		Paylog paylog = new Paylog();
		paylog.setUid(order.getUid());
		paylog.setPayEvent(PayEvent.PAY);
		paylog.setPayType(order.getPayType());
		paylog.setPayTime(order.getPayTime());
		paylog.setTotalFee(order.getTotalFee());
		paylog.setTradeNo(order.getTradeNo());
		paylog.setContent(allparams);
		paylogService.save(paylog);
	}
}
